package IOTWeb.com.handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.utils.HttpRequestFormOtherResolver;
import IOTWeb.com.utils.MGUtil;
import IOTWeb.com.utils.Utils;

/**
 * @author JaridLi
 * 文件保存到mongodb数据库
 */
public class Upload2MongoHandler implements HttpHandler{

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		MGUtil mgUtil = new MGUtil();
		Utils utils = new Utils();
		
		// get body
		Headers headers = exchange.getRequestHeaders();
        int length = Integer.parseInt(headers.getFirst("Content-length"));
        InputStream in = exchange.getRequestBody();
        byte[] body = IOUtils.toByteArray(in, length);
        List<HttpRequestFormOtherResolver.ParamItem> params = HttpRequestFormOtherResolver.resolveForm(headers, body);
        for (HttpRequestFormOtherResolver.ParamItem paramItem : params) {
            if (paramItem.getType().equals("text")) {
                System.out.println(paramItem);
            } else {

            	byte[] bs = new byte[paramItem.getEndIndex()- paramItem.getStartIndex()];
                System.arraycopy(body, paramItem.getStartIndex(), bs, 0, paramItem.getEndIndex()- paramItem.getStartIndex());
        		// 存入数据库
        		try {
        			mgUtil.upload(bs, paramItem.getFilename());
					
        		} catch (IOException e) {
        			System.out.println("io异常");
        			e.printStackTrace();
        		} catch (SQLException e) {
        			System.out.println("sql异常");

        			e.printStackTrace();
        		}
            }
        }

		byte[] responseBody = "上传成功".getBytes("utf-8");

		exchange.sendResponseHeaders(200, responseBody.length);
		OutputStream os = exchange.getResponseBody();
		os.write(responseBody);
		os.close();
		
		
	}

}
